<?php

namespace App\Jobs;

use App\Models\Book;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use EasyWeChat;

class BookStockRemindUserJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $book;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Book $book)
    {
        $this->book = $book;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $officialAccount = EasyWeChat::officialAccount(); // 公众号

        //给关注者发送消息
        $users = \DB::table('book_stock_remind_users')->where('book_id',$this->book->id)->get();
        if(!empty($users))
        {
            foreach ($users as $v)
            {
                $user = \DB::table('users')->where('id',$v->user_id)->first();
                if(!empty($user))
                {
                    $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
                    if(!empty($wechat_user))
                    {
                        $openid = $wechat_user->openid;

                        $first = "你想买的图书《".$this->book->title."》到货了，好书不等人，赶快去看看吧\r\n";
                        $keyword1 = $this->book->title;
                        $keyword2 = "仅剩".$this->book->total_stock."本";
                        $officialAccount->template_message->send([
                            'touser' => $openid,
                            'template_id' => 'EGKj2-sTB8UW3zrOrlI4D2FIuXrjsYl0H_iBNuDYLNE',
                            'url' => '',
                            'miniprogram' => [
                                'appid'     => config('wechat.mini_program.default.app_id'),
                                'pagepath'  => 'pages/remind/remind'
                            ],
                            'data' => [
                                'first'     => $first,
                                'keyword1'  => "《".$keyword1."》",
                                'keyword2'  => $keyword2."\r\n",
                                'remark'    => "如不想收到这本书的到货提醒，请在小程序内「我的」-「到货提醒」中取消这本书的提醒。"
                            ],
                        ]);

                    }
                }
                //\DB::table('book_stock_remind_users')->where('id',$v->id)->delete();
            }
        }
    }
}
